<template>
  <div class="app-container">
    <div style="width: 100%;text-align: right;">
      <el-button size="small" type="primary" icon="el-icon-plus" @click="add" style="margin-right: 16px;">新增</el-button>
    </div>

    <el-divider />

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" stripe>
      <el-table-column fixed label="ID" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.userId }}
        </template>
      </el-table-column>
      <el-table-column label="登录用户名" prop="userName" />
      <el-table-column label="昵称" prop="nickName" />
      <el-table-column label="手机号码" prop="phonenumber" />
      <el-table-column label="账号状态">
        <template slot-scope="scope">
          {{ scope.row.status?(scope.row.status=='1'?'停用':'正常'):'-' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column label="最后登录时间" prop="loginDate" >
        <template slot-scope="scope">
          <template v-if="scope.row.loginDate">{{formatTime(scope.row.loginDate)}}</template>
          <template v-else></template>
        </template>
      </el-table-column>
      <el-table-column label="最后登录ip" prop="loginIp" />
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template slot-scope="scope">
          <span>
            <el-button circle type="success" icon="el-icon-more" size="mini" @click="openDetailDialog(scope.row.userId)" title="详情"></el-button>
            <template v-if="scope.row.userId === myUserId">
              <el-button circle type="primary" icon="el-icon-edit-outline" size="mini" @click="changePassword(scope.row)" title="修改密码"></el-button>
            </template>
            <template v-if="!scope.row.admin && scope.row.userId!==myUserId">
              <el-button circle type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.userId)" title="修改"></el-button>
              <el-button circle type="danger" icon="el-icon-delete" size="mini" @click="del(scope.row.userId)" title="删除"></el-button>
            </template>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="fetchData"  style="text-align: center"/>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'modify' ? '修改' : '新增'">
      <el-form ref="formRef" :model="formData" label-width="120px" label-position="right" v-if="formData" :rules="rules">
        <el-row :gutter="20">
          <template v-if="formData.userId">
            <el-col :span="12">
              <el-form-item label="用户ID">
                <span>{{formData.userId}}</span>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <template v-if="!formData.userId">
                <el-input v-model="formData.userName" placeholder="请输入用户名" />
              </template>
              <template v-else>
                <span>{{formData.userName}}</span>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="!formData.userId">
              <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="formData.phonenumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号状态">
              <el-select v-model="formData.status" placeholder="请选择">
                <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="formData.roleIds" placeholder="请选择" multiple :multiple-limit="1">
                <el-option
                    v-for="item in roleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" maxlength="500"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="detailDialogVisible" title="详情">
      <el-form ref="detailForm" :model="detailData" label-width="120px" label-position="right" v-if="detailData">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ID">
              <span>{{detailData.userId}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名">
              <span>{{detailData.userName}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="昵称">
              <span>{{detailData.nickName}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <span v-for="item in detailData.roles">{{ item.roleName + ' '}} </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名">
              <span>{{detailData.name}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <span> {{detailData.phonenumber}} </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间">
              <span>{{detailData.createTime}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人">
              <span>{{detailData.createBy}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态">
              <span>{{detailData.status === '0' ? '正常' : '禁用'}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <span>{{detailData.remark}}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="pwdDialogVisible" title="修改密码">
      <el-form ref="pwdDataForm" :model="pwdFormData" label-width="120px" label-position="right" v-if="pwdFormData" :rules="pwdRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID">
              <span>{{pwdFormData.userId}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录用户名">
              <span>{{pwdFormData.userName}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="新密码" prop="password">
              <el-input v-model="pwdFormData.password" type="password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="再输一遍" required>
              <el-input v-model="passwordAgain" type="password" placeholder="请再输一遍密码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="pwdDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitNewPwd">
          确定
        </el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import { getUserList, userDetails, addUser, delUser, updateUser} from '@/api/user'
  import { roleList } from '@/api/role'
  import { datetimeFormat } from '@/utils/datetime-util'
  import { isCellPhone, validUsername } from '@/utils/validate'

  export default {
    name: 'User',
    components: {
      Pagination
    },
    data() {
      var checkPhone = (rule, value, callback) => {
        if (!value) {
          // callback(new Error("请输入手机号"));
          callback();
        } else if (!isCellPhone(value)) {//引入methods中封装的检查手机格式的方法
          callback(new Error("请输入正确的手机号!"));
        } else {
          callback();
        }
      };
      var checkUsername = (rule, value, callback) => {
        if (!/^(?![0-9]*$)(?![a-zA-Z]*$)[a-zA-Z0-9]{3,20}$/.test(value)) {
          callback(new Error('账号必须为6-20位字母和数字组合'))
        } else {
          callback()
        }
      }
      var checkPassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码不能少于6位'))
        } else {
          callback()
        }
      }
      var checkNickName = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error('昵称必填'))
        } else {
          callback()
        }
      }
      var checkName = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error('姓名必填'))
        } else {
          callback()
        }
      }
      var checkEmpty = (rule, value, callback) => {
        if (!value) {
          callback(new Error("必填项不能为空！"));
        } else {
          callback();
        }
      }
      var checkEmptyArray = (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error("请至少选择一项！"));
        } else {
          callback();
        }
      }
      return {
        statusOptions: [
          { label: '正常', value: '0' },
          { label: '停用', value: '1' },
        ],
        passwordAgain: '',
        pwdDialogVisible: false,
        pwdFormData:{
          userId: '',
          password: ''
        },
        total: 0,
        list: [],
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 10,
          status: '',
          searchValue: ''
        },
        dialogVisible: false,
        dialogType: 'create',
        loading: false,
        roleOptions: [],
        detailData: null,
        detailDialogVisible: false,
        formData: {
          userName: '',
          password: '',
          nickName: '',
          name: '',
          roleIds: [],
          phonenumber: '',
          status: '0',
          remark: ''
        },
        rules: {
          userName: [{ required:true, validator: checkUsername, trigger:'blur' }],
          name: [{ required:true, validator: checkName, trigger:'blur' }],
          password: [{ required:true, validator: checkPassword, trigger:'blur' }],
          nickName: [{ required:true, validator: checkNickName, trigger:'blur' }],
          roleIds: [
            { type:'array', len:1, required:true, validator: checkEmptyArray, trigger:'blur'}
          ],
          phonenumber: [{ required: false, validator: checkPhone, trigger:'blur' }]
        },
        pwdRules: {
          password: [{ required:true, validator: checkPassword, trigger:'blur' }]
        }
      }
    },
    computed: {
      myUserId() {
        return this.$store.getters.userId;
      }
    },
    created() {
      console.log('my userId', this.myUserId)
      this.getRoleList()
    },
    mounted() {
      this.fetchData()
    },
    methods: {
      formatTime(timeStr) {
        return datetimeFormat('YYYY-mm-dd HH:MM:SS', new Date(timeStr))
      },
      changePassword(row) {
        this.passwordAgain = ''
        this.pwdFormData = {
          userId: row.userId,
          userName: row.userName,
          password: ''
        }
        this.$nextTick(() => {
          if (this.$refs['pwdDataForm']) {
            this.$refs['pwdDataForm'].clearValidate()
          }
        })
        this.pwdDialogVisible = true
      },
      openDetailDialog(userId) {
        userDetails(userId).then(response => {
          if (response.code === 200 ){
            this.detailData = response.data
            this.detailDialogVisible = true
          } else {
            this.$message.error('获取用户详情失败：' + response.msg)
          }
        })
      },
      getRoleList() {
        this.listLoading = true
        let params = {
          pageNum: 1,
          pageSize: 1000,
        }
        roleList(params).then(response => {
          if (response.code === 200) {
            for (let i = 0; i < response.rows.length; i++) {
              this.roleOptions.push({
                value: response.rows[i].roleId,
                label: response.rows[i].roleName,
              })
            }
          }
        })
      },
      search() {
        this.fetchData()
      },
      refresh() {
        this.listQuery = {
          pageNum: 1,
          pageSize: 10,
          status: '',
          searchValue: ''
        }
        this.fetchData()
      },
      fetchData() {
        this.listLoading = true
        getUserList(this.listQuery).then(response => {
          this.list = response.rows
          this.total = response.total
          this.listLoading = false
        })
      },
      add() {
        this.formData = {
          userName: '',
          password: '',
          nickName: '',
          name: '',
          roleIds: [],
          phonenumber: '',
          status: '0',
          remark: ''
        }
        this.dialogVisible = true
        this.dialogType = 'create'
        this.$nextTick(() => {
          this.$refs['formRef'].clearValidate()
        })
      },
      edit(userId) {
        userDetails(userId).then(response => {
          if (response.code === 200 ){
            this.formData = {
              userId: response.data.userId,
              userName: response.data.userName,
              password: response.data.password,
              nickName: response.data.nickName,
              name: response.data.name,
              roleIds: [],
              phonenumber: response.data.phonenumber,
              status: response.data.status,
              remark: response.data.remark
            }
            for (let i = 0; i < response.data.roles.length; i++) {
              this.formData.roleIds.push(response.data.roles[i].roleId)
            }
            this.$nextTick(() => {
              this.dialogVisible = true
              this.dialogType = 'modify'
              if (this.$refs['formRef']) {
                this.$refs['formRef'].clearValidate()
              }
            })
          } else {
            this.$message.error('获取用户详情失败：' + response.msg)
          }
        })
      },
      del(userId) {
        this.$confirm('确认删除该条数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUser(userId).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功！')
              this.fetchData()
            } else {
              this.$message.error('删除失败：' + response.msg)
            }
          })
        })
      },
      submit() {
        this.$refs['formRef'].validate(valid => {
          if (valid) {
            if (!this.formData.userId) {
              // 新增
              addUser(this.formData).then(response => {
                if (response.code === 200) {
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  })
                  this.fetchData()
                  this.dialogVisible = false
                } else {
                  this.$message.error("新增失败：" + response.msg)
                }
              })
            } else {
              // 修改
              updateUser(this.formData).then(response => {
                if (response.code === 200) {
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  })
                  this.fetchData()
                  this.dialogVisible = false
                } else {
                  this.$message.error("新增失败：" + response.msg)
                }
              })
            }
          }
        })
      },
      submitNewPwd() {
        this.$refs['pwdDataForm'].validate(valid => {
          if (valid) {
            if (this.pwdFormData.password !== this.passwordAgain) {
              this.$message.warning("两遍密码不一致！")
              return
            }
            // 修改密码
            updateUser(this.pwdFormData).then(response => {
              if (response.code === 200) {
                this.$message({
                  message: '密码已修改成功',
                  type: 'success'
                })
                this.fetchData()
                this.pwdDialogVisible = false
              } else {
                this.$message.error("修改密码失败：" + response.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
